<template>
  <div class="employee-stock">
    <el-card>
      <template #header>
        <div class="filter-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称或条形码"
            clearable
            style="width: 250px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="categoryFilter" placeholder="商品分类" clearable style="width: 150px">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
          
          <el-select v-model="stockFilter" placeholder="库存状态" clearable style="width: 150px">
            <el-option label="全部" :value="null" />
            <el-option label="库存充足" value="sufficient" />
            <el-option label="库存预警" value="warning" />
            <el-option label="库存不足" value="insufficient" />
          </el-select>
          
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          
          <el-button type="warning" @click="showAlertOnly">
            <el-icon><Warning /></el-icon> 仅显示预警
          </el-button>
        </div>
      </template>
      
      <el-table 
        v-loading="loading" 
        :data="stockList" 
        border
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="getImageUrl(row.image)"
              :preview-src-list="[getImageUrl(row.image)]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px;"
              :hide-on-click-modal="true"
            />
            <span v-else style="color: #999;">无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="barcode" label="条形码" width="150" />
        
        <el-table-column prop="stock" label="当前库存" width="120" sortable>
          <template #default="{ row }">
            <el-tag :type="getStockType(row.stock, row.minStock)">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="minStock" label="预警值" width="100" />
        
        <el-table-column label="库存状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStockType(row.stock, row.minStock)">
              {{ getStockStatus(row.stock, row.minStock) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="提示" min-width="150">
          <template #default="{ row }">
            <div v-if="row.stock === 0" style="color: #F56C6C;">
              <el-icon><WarningFilled /></el-icon> 商品已售罄，请及时补货
            </div>
            <div v-else-if="row.stock <= row.minStock" style="color: #E6A23C;">
              <el-icon><Warning /></el-icon> 库存不足，建议补货
            </div>
            <div v-else style="color: #67C23A;">
              <el-icon><SuccessFilled /></el-icon> 库存充足
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="warning" text @click="handleSetMinStock(row)">
              <el-icon><Setting /></el-icon> 设置预警
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="updateTime" label="最后更新" width="180" />
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: center;"
        @size-change="loadStock"
        @current-change="loadStock"
      />
    </el-card>
    
    <!-- 设置预警值对话框 -->
    <el-dialog v-model="minStockDialogVisible" title="设置库存预警值" width="500px">
      <el-form :model="minStockForm" label-width="120px">
        <el-form-item label="商品名称">
          <span>{{ minStockForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前预警值">
          <span>{{ minStockForm.currentMinStock }}</span>
        </el-form-item>
        <el-form-item label="新预警值" required>
          <el-input-number 
            v-model="minStockForm.newMinStock" 
            :min="0"
            :step="1"
            style="width: 100%"
          />
          <div style="margin-top: 5px; font-size: 12px; color: #999;">
            当库存低于或等于此值时，系统将发出预警提示
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="minStockDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmitMinStock"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 库存统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="8">
        <el-card shadow="hover">
          <el-statistic title="库存预警商品" :value="alertCount">
            <template #prefix>
              <el-icon style="color: #E6A23C;"><Warning /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <el-statistic title="缺货商品" :value="outOfStockCount">
            <template #prefix>
              <el-icon style="color: #F56C6C;"><WarningFilled /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <el-statistic title="库存充足商品" :value="sufficientCount">
            <template #prefix>
              <el-icon style="color: #67C23A;"><SuccessFilled /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Warning, WarningFilled, SuccessFilled, Setting } from '@element-plus/icons-vue'
import { getProductList, updateProduct } from '@/api/product'
import { getCategoryList } from '@/api/category'

const loading = ref(false)
const searchKeyword = ref('')
const categoryFilter = ref(null)
const stockFilter = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const stockList = ref([])
const categories = ref([])
const minStockDialogVisible = ref(false)
const submitLoading = ref(false)

const minStockForm = reactive({
  id: null,
  name: '',
  currentMinStock: 10,
  newMinStock: 10
})

onMounted(() => {
  loadStock()
  loadCategories()
})

const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.data) {
      categories.value = res.data
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadStock = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchKeyword.value,
      categoryId: categoryFilter.value,
      status: 1 // 只查询上架商品
    }
    
    // 根据库存状态筛选
    if (stockFilter.value === 'warning' || stockFilter.value === 'insufficient') {
      params.stockAlert = true
    }
    
    const res = await getProductList(params)
    if (res.data) {
      let list = res.data.records || []
      
      // 前端过滤库存状态
      if (stockFilter.value === 'sufficient') {
        list = list.filter(item => item.stock > item.minStock)
      } else if (stockFilter.value === 'insufficient') {
        list = list.filter(item => item.stock === 0)
      }
      
      stockList.value = list
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载库存失败:', error)
    ElMessage.error('加载库存数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadStock()
}

const showAlertOnly = () => {
  stockFilter.value = 'warning'
  handleSearch()
}

const handleSetMinStock = (row) => {
  minStockForm.id = row.id
  minStockForm.name = row.name
  minStockForm.currentMinStock = row.minStock || 10
  minStockForm.newMinStock = row.minStock || 10
  minStockDialogVisible.value = true
}

const handleSubmitMinStock = async () => {
  if (minStockForm.newMinStock < 0) {
    ElMessage.warning('预警值不能为负数')
    return
  }
  
  submitLoading.value = true
  try {
    await updateProduct({
      id: minStockForm.id,
      minStock: minStockForm.newMinStock
    })
    
    ElMessage.success('预警值设置成功')
    minStockDialogVisible.value = false
    loadStock()
  } catch (error) {
    ElMessage.error(error.message || '预警值设置失败')
  } finally {
    submitLoading.value = false
  }
}

const getStockType = (stock, minStock) => {
  if (stock === 0) return 'danger'
  if (stock <= minStock) return 'warning'
  return 'success'
}

const getStockStatus = (stock, minStock) => {
  if (stock === 0) return '缺货'
  if (stock <= minStock) return '预警'
  return '正常'
}

const tableRowClassName = ({ row }) => {
  if (row.stock === 0) return 'danger-row'
  if (row.stock <= row.minStock) return 'warning-row'
  return ''
}

const getImageUrl = (image) => {
  if (!image) return ''
  if (image.startsWith('http://') || image.startsWith('https://')) return image
  // 图片文件直接从后端服务器获取
  return `http://localhost:8080/${image.startsWith('/') ? image.slice(1) : image}`
}

// 统计数据
const alertCount = computed(() => {
  return stockList.value.filter(item => 
    item.stock > 0 && item.stock <= item.minStock
  ).length
})

const outOfStockCount = computed(() => {
  return stockList.value.filter(item => item.stock === 0).length
})

const sufficientCount = computed(() => {
  return stockList.value.filter(item => item.stock > item.minStock).length
})
</script>

<style lang="scss" scoped>
.employee-stock {
  .filter-bar {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
}

:deep(.el-table) {
  .danger-row {
    background-color: #fef0f0;
  }
  
  .warning-row {
    background-color: #fdf6ec;
  }
}
</style>
